﻿using Cinchoo.Core;
using Cinchoo.Core.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChoWorkflowServer.Model
{
    public static class ChoDataModelFactory
    {
        private readonly static ChoModelSettings _modelSettings = new ChoModelSettings();

        public static IChoDataModel New()
        {
            IChoDataModel model = null;

            ChoWFServerCmdLineArgsObject cmd = new ChoWFServerCmdLineArgsObject();
            if (cmd.DebugMode)
                model = new ChoNullDataModel();
            else
            {
                Type t = _modelSettings.DataModelType;
                if (cmd.RunAsPeer)
                {
                    t = _modelSettings.WCFDataModelType;
                    if (t == null)
                    throw new ApplicationException("WCF Data model type is missing.");
                }
                else
                {
                    if (t == null)
                        t = Type.GetType("ChoWorkflowServer.ModelSqlite.ChoDataModel, ChoWorkflowServer.ModelSqlite");
                }

                if (t == null)
                    throw new ApplicationException("Data model type is missing.");

                model = ChoActivator.CreateInstance(t) as IChoDataModel;

                if (model == null)
                    throw new ApplicationException("Can't find {0} data model.".FormatString(t.FullName));
            }

            return model;
        }

        public static Type DataModelType
        {
            get
            {
                Type t = _modelSettings.DataModelType;
                if (t == null)
                    t = Type.GetType("ChoWorkflowServer.ModelSqlite.ChoDataModel, ChoWorkflowServer.ModelSqlite");
                if (t == null)
                    throw new ApplicationException("Data model type is missing.");

                return t;
            }
        }
    }
}
